package com.gorkr.labuladong.data_struct.linked_list;

import org.junit.jupiter.api.Test;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @author gorkr
 * @date 2022/09/17 15:01
 **/
public class M143ReorderList {

    class ListNode {

        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public void reorderList(ListNode head){
        // 中间节点
        ListNode mid = findMid(head);
        ListNode reverseHead = mid.next;
        // 断开
        mid.next = null;
        ListNode last = reverse(reverseHead);
        merge(head,last);
    }

    private void merge(ListNode head, ListNode last) {
        ListNode p =head, q =last;
        while (p!=null&&q!=null){
            ListNode tmp = p.next;
            ListNode tmq = q.next;
            p.next = q;

            if(tmp!=null){
                q.next = tmp;
            }
            p = tmp;
            q = tmq;
        }
    }

    // 反转链表 返回反转后的头节点
    public ListNode reverse(ListNode head) {
        // base case
        if(head==null||head.next==null){
            return head;
        }

       ListNode last = reverse(head.next);
        head.next.next = head;
        head.next = null;

        return last;
    }

    // 寻找中间节点
    private ListNode findMid(ListNode head){
        ListNode slow = head;
        ListNode fast = head;

        while (fast.next!=null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }



    // 速度慢 不太行 本质上就是找了辅助空间 能随机访问了
    public void myReorderList(ListNode head) {
        ListNode p = head;
        Stack<ListNode> stack = new Stack<>();
        int size = 0;
        while (p != null) {
            stack.push(p);
            p = p.next;
            size++;
        }
        // 重新指向头
        p = head;

        boolean out = true;
        while (stack.size()>=size/2) {
            ListNode popd = stack.pop();
            popd.next = p.next;
            p.next = popd;
            p = popd.next;
        }
        p.next=null;
    }

    @Test
    public void test(){
        ListNode head = new ListNode(1);
//        head.next = new ListNode(2);
//        head.next.next = new ListNode(3);
//        head.next.next.next = new ListNode(4);

//        ListNode reverse = reverse(head);
//
//        System.out.println(reverse.val);


        reorderList(head);
    }



}


    